package os.t3;

import java.util.concurrent.Semaphore;

public class Resources {
    public Semaphore rMutex=new Semaphore(1);//读者锁,锁的是readCount,因为它是一个公共的变量,防止多线程同时操作readCount
    public Semaphore wMutex=new Semaphore(1);//写者锁
    public int readCount=0;//用于读者计数，读者也是临界资源


    public void write() throws InterruptedException {

        wMutex.acquire();//锁住写者
        System.out.println("写者正在写..."+Thread.currentThread().getName());
        wMutex.release();//释放写者
        Thread.sleep(100);

    }
    public void read() throws InterruptedException{

        rMutex.acquire();//获取读者资源
        if (readCount == 0) {//如果是第一个读者来了
            wMutex.acquire();//获取写着资源，防止在读的时候有写着写
        }
        readCount++;//读者数量加1
        rMutex.release();//释放读者资源

        System.out.println(readCount + "号读者在读..." + Thread.currentThread().getName());

        rMutex.acquire();
        readCount--;
        if (readCount == 0) {//最后一个读者
            wMutex.release();//释放写者资源
        }
        rMutex.release();
        Thread.sleep(100);

    }


}
